﻿//定义js命名空间
Ext.namespace("Infrastructure");

//基本的From
Infrastructure.BasePanel = Ext.extend(Ext.Panel, {
	border: false,
	labelAlign: 'right',
	labelWidth: 90, // 注意 使用时 如果有表单内组件有特殊标签名称长度很大 替换合适的标签长度
	frame: true,
	layout: 'form',
	bodyStyle: 'padding:5px 5px 0'
});

//基本的From
Infrastructure.BaseForm = Ext.extend(Ext.form.FormPanel, {
	dataId: '',
	dataRecord: null,
	border: false,
	waitMsgTarget: true,
	labelAlign: 'right',
	labelWidth: 90, // 注意 使用时 如果有表单内组件有特殊标签名称长度很大 替换合适的标签长度
	frame: true,
	bodyStyle: 'padding:5px 5px 0',
	buttonAlign: 'center',
	submitUrl: null,
	submitMsg: '确定要将记录保存到服务器吗?',
	initComponent: function () {
		if (this.dataRecord != null)
			this.dataId = this.dataRecord.data.Id;
		Infrastructure.BaseForm.superclass.initComponent.call(this);
		//定义保存后执行的事件
		this.addEvents('afterSave');
		if (this.dataRecord != null)
			this.form.loadRecord(this.dataRecord);
	},

	/****************** 
	* user function 
	******************/

	//提交表单
	saveItem: function (submitUrl) {
		var itemForm = this;
		var dataId = this.dataId;
		var url = (submitUrl == undefined ? itemForm.submitUrl : submitUrl);
		if (url == undefined || url == '')
			JsHelper.ShowError('未定义提交服务。请联系管理员。');
		if (itemForm.getForm().isValid()) {
			//确认后提交
			JsHelper.Confirm(this.submitMsg, function (btn) {
				if (btn == 'yes') {
					itemForm.getForm().submit({
						waitMsg: '正在提交....',
						url: url,
						params: {
							'Id': (dataId == null) ? '' : dataId
						},
						success: function (form, action) {
							//返回结果后触发保存事件
							JsHelper.ShowInfo('记录保存成功!');
							itemForm.fireEvent('afterSave', itemForm, true);
						},
						failure: function (form, action) {
							JsHelper.ShowActionError(action);
						}
					});
				}
			});
		}
	}
});

Infrastructure.BaseWindow = Ext.extend(Ext.Window, {
	dataId: null,
	dataRecord: null,
	dataForm: null,
	menuId: '000000',
	submitUrl: '',
	submitMsg: '确定要保存吗?',
	title: 'application base window',
	iconCls: 'application',
	width: 650,
	resizable: false,
	constrain: true,
	autoHeight: true,
	modal: true,
	closeAction: 'close',
	plain: true,
	buttonAlign: 'center',
	initComponent: function () {
		var dataWin = this;
		var submitMenuId = '00';
		if (this.dataForm != null)
			submitMenuId = ((this.dataForm.dataId == null || this.dataForm.dataId == '') && this.dataForm.dataRecord == null) ? '01' : '02';

		Ext.applyIf(this, {
			items: [this.dataForm],

			buttons: [new Ext.ux.SubmitBtn({
				menuid: this.menuId + submitMenuId,
				handler: function () {
					this.dataForm.saveItem(this.dataForm.submitUrl)
				},
				scope: dataWin
			}), new Ext.ux.CancelBtn({
				hidden: this.menuId == '000000',
				handler: function () {
					dataWin.hide();
				}
			})]
		});
		Infrastructure.BaseWindow.superclass.initComponent.call(this);
	}
});

//文件上传Form
Infrastructure.FileUploadWin = Ext.extend(Ext.Window, {
	//user Prop
	uploadUrl: '',
	emptyText: '请选择上传的文件...',
	fieldLabel: '文件',
	confirmMsg: '要上传文件吗?',
	//public Prop
	title: '文件上传',
	iconCls: 'application_get',
	width: 600,
	autoHeight: true,
	modal: true,
	closeAction: 'close',
	plain: true,
	//initComponent
	initComponent: function () {
		var upWin = this;

		var msg = function (title, msg) {
			Ext.Msg.show({
				title: title,
				msg: msg,
				minWidth: 200,
				modal: true,
				icon: Ext.Msg.INFO,
				buttons: Ext.Msg.OK
			});
		};

		var fp = new Infrastructure.BaseForm({
			fileUpload: true,
			autoHeight: true,
			waitMsgTarget: false,
			buttonAlign: 'right',
			defaults: {
				anchor: '95%',
				allowBlank: false,
				msgTarget: 'side'
			},
			items: [{
				xtype: 'fileuploadfield',
				id: 'form-file',
				emptyText: this.emptyText,
				fieldLabel: this.fieldLabel,
				name: 'file-path',
				buttonText: '',
				buttonCfg: {
					iconCls: 'upload-icon'
				}
			}],
			buttons: [{
				text: 'Save',
				handler: function () {
					if (fp.getForm().isValid()) {
						JsHelper.Confirm(upWin.confirmMsg, function (btn) {
							if (btn == 'yes') {
								fp.getForm().submit({
									url: upWin.uploadUrl,
									waitMsg: '正在处理上传文件......',
									success: function (fp, o) {
										//返回结果后触发保存事件
										if (o.result.success == false) {
											JsHelper.ShowError('操作失败:' + o.result.message);
										} else {
											JsHelper.ShowInfo('上传成功。' + o.result.message);
											upWin.fireEvent('uploadSuccess', fp, true);
										}
									},
									failure: function (form, action) {
										JsHelper.ShowActionError(action);
									}
								});
							}
						});
					}
				}
			}, {
				text: 'Reset',
				handler: function () {
					fp.getForm().reset();
				}
			}]
		});
		Ext.apply(this, {
			items: [fp]
		});
		Infrastructure.FileUploadWin.superclass.initComponent.call(this);
		//定义保存后执行的事件
		this.addEvents('uploadSuccess');
	}
});

//基本分页栏
Infrastructure.BasePagingToolbar = Ext.extend(Ext.PagingToolbar, {
	displayInfo: true,
	displayMsg: '{0}到{1}条，共{2}条',
	emptyMsg: '没有数据显示',
	pageSize: ALL_PAGESIZE_SETTING,

	initComponent: function () {
		Infrastructure.BasePagingToolbar.superclass.initComponent.call(this);
	}
});

//基础GridPanel
Infrastructure.BaseGridPanel = Ext.extend(Ext.grid.GridPanel, {
	//基本处理Url
	menuPId: '0000',
	baseUrl: '',
	//提交保存Url
	formSubmitUrl: '',
	//提交保存提示信息
	formSubmitMsg: '确定要保存吗?',
	//记录编辑窗口
	itemEditWin: null,
	itemGridEditor: new Ext.ux.grid.RowEditor(),
	itemEditRecord: null,
	//列显示控制
	columnMask: '',
	//Pagebar 显示
	pageBarQuery: true,

	// Property
	stripeRows: true,
	frame: true,
	border: true,
	layout: 'fit',
	loadMask: true,
	enableColumnMove: false,
	viewConfig: {
		autoFill: true
	},

	//constructor
	initComponent: function () {
		var itemGrid = this;

		var pagebBar = new Ext.PagingToolbar({
			displayInfo: true,
			displayMsg: '{0}到{1}条，共{2}条',
			emptyMsg: '没有数据显示',
			pageSize: itemGrid.store.baseParams['limit'],
			store: this.store,
			plugins: this.plugins,
			items: ['-', {
				xtype: 'tbarresetbtn',
				minWidth: 50,
				handler: function () {
					itemGrid.filters.clearFilters();
				}
			}, {
				xtype: 'tbarselectRetbtn',
				hidden: !Ext.isDefined(itemGrid.events.afterchoose),
				minWidth: 50,
				ref: 'btnSel',
				handler: function () {
					itemGrid.tbarSelect("返回选择的记录吗?");
				}
			}, {
				xtype: 'tbaraddbtn',
				menuid: itemGrid.menuPId + '01',
				minWidth: 50,
				hidden: !Ext.isDefined(itemGrid.addEntity),
				ref: 'btnAdd',
				handler: function () {
					itemGrid.addEntity();
				}
			}, {
				id: 'bbarDelbtn',
				xtype: 'tbardelbtn',
				ref: 'btnDel',
				menuid: itemGrid.menuPId + '03',
				minWidth: 50,
				handler: function () {
					itemGrid.delEntity();
				}
			}, {
				xtype: 'trigger',
				width: 150,
				triggerClass: 'x-form-search-trigger', //按钮样式
				hidden: !itemGrid.pageBarQuery,
				readOnly: false, //只读
				emptyText: '快速查找',
				onTriggerClick: function () {
					itemGrid.qryList(this.getValue());
				},
				listeners: {
					specialkey: function (field, e) {
						if (e.getKey() == e.ENTER) {
							itemGrid.qryList(field.getValue());
						}
					}
				}
			}]
		});

		var selModel = new Ext.grid.CheckboxSelectionModel({
			header: '',
			singleSelect: false,
			listeners: {
				'selectionchange': function (sm) {
					// 控制工具栏按钮是否可用
					var bottomToolbar = sm.grid.getBottomToolbar();
					bottomToolbar.btnDel.setDisabled(sm.getCount() < 1);
					bottomToolbar.btnSel.setDisabled(sm.getCount() < 1);
				}
			}
		});

		Ext.applyIf(this, {
			sm: selModel,
			bbar: pagebBar,
			listeners: {
				'rowdblclick': function (grid, rowIndex, e) {
					if (Ext.isDefined(grid.showEntity)) {
						grid.showEntity(grid, rowIndex);
					}
				}
			}
		});

		Infrastructure.BaseGridPanel.superclass.initComponent.call(this);
		//定义选择后执行的事件
		//colMask
		for (var i = 0; i < this.colModel.getColumnCount(); i++) {
			this.colModel.getColumnAt(i).hidden = (this.columnMask.charAt(i) != '' && this.columnMask.charAt(i) == 0);
		}
		this.addEvents('afterChoose');
	},

	/***************
	User Command 
	***************/

	/*
	//分页按钮添加
	addEntity:function(){},
	//分页按钮删除
	delEntity:function(){},
	*/

	insertNewEntity: function (insertUrl, newEvent) {
		var itemGrid = this;
		//加载进度条
		Ext.MessageBox.show({
			msg: '正在处理...',
			progressText: '处理中...',
			width: 300,
			wait: true,
			waitConfig: { interval: 1000 }
		});
		Ext.Ajax.request({
			url: insertUrl,
			success: function (response, opts) {
				Ext.MessageBox.hide();
				var result = Ext.util.JSON.decode(response.responseText);
				if (result.success == false) {
					JsHelper.ShowError('系统错误:' + result.msg);
				} else {
					itemGrid.fireEvent(newEvent, result.id, true);
				}
			},
			failure: function (form, action) {
				Ext.MessageBox.hide();
				JsHelper.ShowActionError(action);
			}
		});
	},

	addNewEntity: function (sqnocd, sqnodp, newEvent) {
		var itemGrid = this;
		Ext.Ajax.request({
			url: '/Main/GetNewID',
			params: {
				'sqnocd': sqnocd,
				'sqnodp': sqnodp
			},
			success: function (response, opts) {
				var result = Ext.util.JSON.decode(response.responseText);
				if (result.success == false) {
					JsHelper.ShowError('申请流水号失败:' + result.msg);
				} else {
					itemGrid.fireEvent(newEvent, result.id, true);
				}
			},
			failure: function (form, action) {
				JsHelper.ShowActionError(action);
			}
		});
	},

	insertEntity: function () {
		var itemGrid = this;
		var rd = new itemGrid.store.recordType();
		if (this.itemEditRecord != null)
			rd = this.itemEditRecord.copy();
		this.itemGridEditor.stopEditing();
		itemGrid.store.insert(0, rd);
		this.itemGridEditor.startEditing(0);
	},

	// 删除选定
	delEntity: function () {
		var itemGrid = this;
		var itemGridStore = this.store;
		JsHelper.DelConfirm(function (btn) {
			if (btn == 'yes') {
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					itemGridStore.remove(r);
				}
			}
		});
	},

	// 查询
	qryList: function (q_query) {
		var itemGrid = this;
		if (!Ext.isDefined(q_query)) {
			q_query = Ext.getCmp('q_query').getValue();
		}
		itemGrid.store.load({
			params: {
				start: 0,
				limit: itemGrid.store.params['limit'],
				q_query: q_query
			}
		})
	},

	// 选定记录返回
	tbarSelect: function (confirmMsg) {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('未选择记录.');
			return -1;
		}
		JsHelper.Confirm(confirmMsg, function (btn) {
			if (btn == 'yes') {
				itemGrid.fireEvent('afterChoose', selRecord, true);
			}
		});
	},

	// 提交选定记录..
	tbarSubmit: function (submitUrl, confirmMsg, successMsg, successEvent) {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('未选择记录.');
			return -1;
		}
		var selId = selRecord.data.Id;
		JsHelper.Confirm(confirmMsg, function (btn) {
			if (btn == 'yes') {
				var ids = [];
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					ids.push(r.data.Id);
				}
				//加载进度条
				Ext.MessageBox.show({
					msg: '正在提交数据到中心服务器...',
					progressText: '保存数据...',
					width: 300,
					wait: true,
					waitConfig: { interval: 1000 }
				});
				Ext.Ajax.request({
					url: submitUrl,
					params: {
						'Ids': ids.toString()
					},
					success: function (response, opts) {
						Ext.MessageBox.hide();
						var result = Ext.util.JSON.decode(response.responseText);
						if (result.success == false) {
							JsHelper.ShowError('操作失败:' + result.msg);
						} else {
							if (Ext.isDefined(successEvent))
								itemGrid.fireEvent(successEvent, itemGrid, true);
							else
								itemGrid.store.reload();
							Ext.Msg.alert('提示,操作成功', '成功。' + successMsg);
						}
					},
					failure: function (form, action) {
						Ext.MessageBox.hide();
						JsHelper.ShowActionError(action);
					}
				});
			}
		});
	}
});

Infrastructure.BaseGridEditor = Ext.extend(Ext.ux.grid.RowEditor, {
	// 权限控制Menuid
	menuid: '',
	listeners: {
		beforeedit: function (thiz, rowIndex) {
			// 用户权限检查
			isPermit = !(this.menuid != '' && CurrentUserMenuPermission.data.keys.indexOf(this.menuid) < 0);
			// 双击时是否行编辑
			isEditByRow = this.grid.events.rowdblclick.listeners == undefined;
			// 新增记录才编辑
			isNewRecord = this.grid.store.getAt(rowIndex).data.Id == undefined;
			return isPermit && (isNewRecord || isEditByRow);
		},
		canceledit: function (thiz) {
			if (thiz.record.data.Id == undefined)
				thiz.grid.store.remove(thiz.record);
		}
	}
});

//数据格式
Infrastructure.NcArray = new Array(
	{ name: 'Id', type: 'string' },
	{ name: 'Name', type: 'string' },
	{ name: 'Code', type: 'string' }
);

//BaseJsonReader
Infrastructure.BaseJsonReader = Ext.extend(Ext.data.JsonReader, {
	constructor: function (cfg) {
		cfg = cfg || {};
		Infrastructure.BaseJsonReader.superclass.constructor.call(this, Ext.apply({
			root: 'data'
		}, cfg));
	}
});

//BaseJsonStore
Infrastructure.BaseJsonStore = Ext.extend(Ext.data.JsonStore, {
	QryUrl: null, //查询Url
	UpdUrl: null, //更新记录Url
	DelUrl: null, //删除记录Url	
	constructor: function (cfg) {
		cfg = cfg || {};
		Infrastructure.BaseJsonStore.superclass.constructor.call(this, Ext.applyIf(this, {
			url: this.QryUrl,
			remoteSort: true,
			baseParams: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING
			},
			root: 'data',
			totalProperty: 'total',
			listeners: {
				'update': function (thiz, record, operation) {
					var model = record.data;
					if (operation == Ext.data.Record.EDIT && !record.getChanges().Id) {
						//加载进度条
						Ext.MessageBox.show({
							msg: '正在提交数据到中心服务器...',
							progressText: '保存数据...',
							width: 300,
							wait: true,
							waitConfig: { interval: 1000 }
						});
						Ext.Ajax.request({
							url: this.UpdUrl,
							params: model,
							success: function (response, opts) {
								Ext.MessageBox.hide();
								var result = Ext.util.JSON.decode(response.responseText);
								if (result.success) {
									if (!record.get('Id'))
										record.set('Id', result.id);
									thiz.commitChanges();
								} else {
									JsHelper.ShowError(result.msg);
									thiz.rejectChanges();
								}
								thiz.reload();
							},
							failure: function (form, action) {
								Ext.MessageBox.hide();
								JsHelper.ShowActionError(action);
							}
						});
					}
				},
				'remove': function (thiz, record, index) {
					refStore = this;
					if (record.data.Id != null && record.data.Id != '') {
						concateStr = this.DelUrl.indexOf('?') == -1 ? '?' : '&';
						Ext.Ajax.request({
							url: this.DelUrl + concateStr + 'Id=' + record.data.Id,
							success: function (response, opts) {
								var result = Ext.util.JSON.decode(response.responseText);
								if (result.success == false) {
									JsHelper.ShowError(result.msg);
									refStore.insert(0, record);
								}
							},
							failure: function (form, action) {
								JsHelper.ShowActionError(action);
							}
						});
					}
				}
			}
		}));
	}
});

//一般的Name-Code store
Infrastructure.NcStore = Ext.extend(Ext.data.JsonStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		Infrastructure.NcStore.superclass.constructor.call(this, Ext.apply({
			root: 'data',
			totalProperty: 'total',
			fields: Infrastructure.NcArray
		}, cfg));
	}
});

//用户Store
Infrastructure.UserJsonStore = Ext.extend(Infrastructure.NcStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		Infrastructure.UserJsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/InfraHospUser/GetPlist'
		}, cfg));
	}
});

//用户Combox
Infrastructure.UserCombo = Ext.extend(Ext.ux.IdcComboBox, {
	constructor: function (cfg) {
		userCombx = this;
		cfg = cfg || {};
		UserStore = new Infrastructure.UserJsonStore();
		Infrastructure.UserCombo.superclass.constructor.call(this, Ext.apply({
			store: UserStore,
			width: 150,
			listWidth: 200
		}, cfg));
		//重新设置当前值
		UserStore.load({
			callback: function () {
				cvalue = userCombx.getValue();
				if (cvalue != "")
					userCombx.setValue(cvalue);
			}
		});
	}
});
Ext.reg('usercombo', Infrastructure.UserCombo);


//机构部门清单Store
Infrastructure.DeptJsonStore = Ext.extend(Infrastructure.NcStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		Infrastructure.DeptJsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/InfraHospUser/GetDeptList'
		}, cfg));
	}
});

//部门Store
Infrastructure.DeptStore = new Infrastructure.DeptJsonStore({
	autoLoad: true
});

//机构下拉Combox
Infrastructure.DeptCombo = Ext.extend(Ext.ux.IdcComboBox, {
	constructor: function (cfg) {
		deptcombx = this;
		cfg = cfg || {};
		DeptStore = new Infrastructure.DeptJsonStore();
		Infrastructure.DeptCombo.superclass.constructor.call(this, Ext.apply({
			store: DeptStore,
			width: 150,
			listWidth: 200
		}, cfg));
		//重新设置当前值
		DeptStore.load({
			callback: function () {
				cvalue = deptcombx.getValue();
				if (cvalue != "")
					deptcombx.setValue(cvalue);
			}
		});
	}
});
Ext.reg('deptcombo', Infrastructure.DeptCombo);

//字典Store
Infrastructure.DictJsonStore = Ext.extend(Infrastructure.NcStore, {
	category: '',
	constructor: function (cfg) {
		cfg = cfg || {};
		Infrastructure.DeptJsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/InfraDictionary/GetPlistByCategoryCode?Code=' + cfg.category
		}, cfg));
	}
});

//字典下拉Combox
Infrastructure.DictCombo = Ext.extend(Ext.ux.DicComboBox, {
	category: '',
	constructor: function (cfg) {
		cfg = cfg || {};
		var DictStore = new Infrastructure.DictJsonStore({
			category: cfg.category
		});
		DictStore.load();
		Infrastructure.DictCombo.superclass.constructor.call(this, Ext.apply({
			store: DictStore,
			width: 150,
			listWidth: 200
		}, cfg));
	}
});
Ext.reg('dictcombo', Infrastructure.DictCombo);

//状态StateJsonStore
Infrastructure.StateJsonStore = Ext.extend(Ext.data.JsonStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		Infrastructure.StateJsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/InfraHospUser/GetState',
			id: 'Value',
			fields: ['Key', 'Value']
		}, cfg));
	}
});

var InfrastructureStateStore = new Infrastructure.StateJsonStore();
InfrastructureStateStore.load();

//状态Combox
Infrastructure.StateCombo = Ext.extend(Ext.ux.BaseComboBox, {
	fieldLabel: '状态',
	width: 150,
	name: 'State',
	hiddenName: 'State',
	valueField: 'Value',
	displayField: 'Key',
	constructor: function (cfg) {
		cfg = cfg || {};
		//var StateStore = new Infrastructure.StateJsonStore();
		//StateStore.load();
		Infrastructure.DictCombo.superclass.constructor.call(this, Ext.apply({
			store: InfrastructureStateStore
		}, cfg));
	}
});
Ext.reg('statecombo', Infrastructure.StateCombo);
